package com.pro.framework.api.util.inner;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 简单基于固定窗口的限流器（单位：秒）
 */
public class SimpleRateLimiter {

    private final int maxPermitsPerSecond;
    private final AtomicInteger counter = new AtomicInteger(0);
    private volatile long currentSecond = System.currentTimeMillis() / 1000;

    public SimpleRateLimiter(int permitsPerSecond) {
        this.maxPermitsPerSecond = permitsPerSecond;
    }

    /**
     * 阻塞式获取许可
     */
    public synchronized void acquire() {
        while (!tryAcquire()) {
            try {
                Thread.sleep(5); // 等待再试
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException("限流中断", e);
            }
        }
    }

    /**
     * 尝试获取许可，true 表示允许，false 表示被限流
     */
    public synchronized boolean tryAcquire() {
        long now = System.currentTimeMillis() / 1000;
        if (now != currentSecond) {
            currentSecond = now;
            counter.set(0);
        }

        if (counter.incrementAndGet() <= maxPermitsPerSecond) {
            return true;
        } else {
            return false;
        }
    }
}
